<template>
    <el-tooltip :disabled="!visible" :content="title" placement="top-start">
        <div @mouseenter="mouseenter" @mouseleave="visible = false">
            <!-- 二级联动品牌车系选择 -->
            <el-cascader ref="cascaderRef" :disabled="disabled" v-model="classesAndStudent" :placeholder="placeholder"
                         clearable :props="props" :options="cascaderOptions" filterable
                         @change="handleClassChange" style="width:100%;">
            </el-cascader>
        </div>
    </el-tooltip>
</template>

<script>
import {getBrandNames, getSeriesName, getModelName,} from "../../api/system/linkageSelect.js";

export default {
    name: 'LinkageSelect2',
    // props: ['placeholder', 'value', 'checkStrictly'],
    props: {
        placeholder: {
            type: String,
            default: '请选择'
        },
        value: {
            type: Array,
            default: () => {
                return []
            }
        },
        checkStrictly: {
            type: Boolean,
            default: true
        },
        disabled: {
            type: Boolean,
            default: false
        }
    },
    model: {
        prop: 'value',
        event: 'dateChange'
    },
    watch: {
        value: {
            handler(val, old) {
                // console.log('handler', val, old)
                this.classesAndStudent = val

                // this.classesAndStudent = val?.map((item, index) => {
                //     if (item instanceof Object) {
                //         return item.id + "_" + index
                //     } else {
                //         return item + "_" + index
                //
                //     }
                // }) ?? []
                // console.log('this.classesAndStudent', this.classesAndStudent)
            },
            deep: true,
            immediate: true
        },
    },

    data() {
        return {
            brandList: [],
            seriesList: [],
            modelList: [],
            props: {
                // checkStrictly: true,
                // // emitPath: true,
                // lazy: true, //	是否动态加载子节点，需与 lazyLoad 方法结合使用
                // lazyLoad: this.handleGetClassOrStudent, //懒加载调用的方法
            },

            classesAndStudent: [],
            visible:false,
            title:"",
            cascaderOptions:[]
        }
    },
    async created() {
        const bList = await getBrandNames({brandName: ""})
        const sList = await getSeriesName(-1)

        this.cascaderOptions = this.createCascaderOptions(sList, bList);
        // console.log('this.cascaderOptions', this.cascaderOptions)
    },
    mounted() {
        this.props.checkStrictly = this.checkStrictly ?? true
    },
    methods: {
        createCascaderOptions(sList, bList) {
            // 将bList转换成map便于查找
            const bMap = {};
            bList.forEach((item) => {
                bMap[item.id] = { value: item.id, label: item.name, children: [] };
            });

            // 遍历sList并根据brandId与bList的id对应添加到children数组中
            sList.forEach((item) => {
                if (bMap.hasOwnProperty(item.brandId)) {
                    bMap[item.brandId].children.push({
                        value: item.id,
                        label: item.name
                    });
                }
            });

            // 过滤掉没有子选项的项并输出结果
            return Object.values(bMap).filter(item => item.children.length > 0);
        },
        mouseenter() {
            // console.log('this.title', this.title, this.visible)
            // 这里按需求定义的是字符超过10个时，框框显示不全时才显示文字提示
            if (this.title && this.title.length>10) {
                // this.visible = true
                this.visible = false//先不要了
            } else {
                this.visible = false
            }
        },

        // //联级选择器获取数据
        handleGetClassOrStudent(node, resolve) {
            //node相当于点击的选项，其中有上一级的信息
            //第一次调用时 node中什么也没有
            //resolve() 返回的内容是子选项

            const {data, level, parent} = node;

            // console.log('node', node)

            if (level == 0) {
                getBrandNames({brandName: ""}).then(res => {
                    this.brandList = res
                    const nodes = Array.from(res, item => ({
                        value: item.id + "_0",
                        label: item.name,
                        objs: item,
                        leaf: false
                    }))
                    resolve(nodes)

                })
            } else if (level == 1) {
                getSeriesName(data.value.split("_")[0]).then(res => {
                    this.seriesList = res

                    const nodes = Array.from(res, item => ({
                        value: item.id + "_1",
                        label: item.name,
                        objs: item,
                        leaf: true
                    }))
                    resolve(nodes)

                })
            }
            // else if (level == 2) {
            //     getModelName(data.value.split("_")[0]).then(res => {
            //         this.modelList = res
            //         const nodes = Array.from(res, item => ({
            //             value: item.id + "_2",
            //             label: item.name,
            //             objs: item,
            //             leaf: true
            //         }))
            //         resolve(nodes)
            //     })
            // }
            else {
                resolve()
            }
        },


        //选择器选择后触发
        handleClassChange(node, resolve) {

            this.$refs.cascaderRef.panel.clearCheckedNodes();

            const selectedData = this.$refs?.cascaderRef?.getCheckedNodes()??[];
            if(selectedData && selectedData.length > 0){
                this.commitResult(selectedData);
            }else {
                this.$nextTick(()=>{
                    const selectedData2 = this.$refs?.cascaderRef?.getCheckedNodes()??[];
                    this.commitResult(selectedData2)
                })
            }
            // console.log('Selected data:', selectedData);


            //   for (let nodeKey in node) {
            //       node[nodeKey] = {
            //           id:node[nodeKey].split("-")[0],
            //           name:0==nodeKey?this.brandList.find(item=>item.id==(node[0].split("-")[0]))?.name:
            //               1==nodeKey?this.seriesList.find(item=>item.id==(node[1].split("-")[0]))?.name:
            //                   this.modelList.find(item=>item.id==(node[2].split("-")[0]))?.name
            //       }
            //   }
            // this.$emit('changeNode', node)
        },

        commitResult(selectedData){
            // console.log('Selected data:', selectedData);
            let result = []
            if (selectedData && selectedData.length > 0) {
                let {path, pathLabels} = selectedData[0];

                // for (let nodeKey in node) {
                //     node[nodeKey] = {
                //         id:path[nodeKey].split("_")[0],
                //         name:pathLabels[nodeKey]
                //     }
                // }

                this.title = pathLabels.join(" / ")

                result = path.map((item, index) => {
                    return {
                        // id: item.split("_")[0],
                        id: item,
                        name: pathLabels[index]
                    }
                })
            }else {
                this.title = ""
            }
            this.$emit('changeNode', result)
        }



    }


}

</script>

<style lang="scss" scoped></style>
